<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Request;
use think\Session;

class Login extends  Controller
{

    public function _initialize()
    {
        header('Content-Type:text/html; charset=utf-8');
        //判断用户是否登录
        //判断权限
        //登录有效期
    }

    /**
     * 获取用户真实 IP
     */
    public function getIP(){
        static $realip;
        if (isset($_SERVER)){
            if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
                $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
            } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
                $realip = $_SERVER["HTTP_CLIENT_IP"];
            } else {
                $realip = $_SERVER["REMOTE_ADDR"];
            }
        } else {
            if (getenv("HTTP_X_FORWARDED_FOR")){
                $realip = getenv("HTTP_X_FORWARDED_FOR");
            } else if (getenv("HTTP_CLIENT_IP")) {
                $realip = getenv("HTTP_CLIENT_IP");
            } else {
                $realip = getenv("REMOTE_ADDR");
            }
        }
        return $realip;
    }

    /**
     * 获取 IP  地理位置
     * 淘宝IP接口
     * @Return: array
     */
    function getCity($ip = '')
    {
        if($ip == ''){
            $url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json";
            $ip=json_decode(file_get_contents($url),true);
            $data = $ip;
        }else{
            $url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
            $ip=json_decode(file_get_contents($url));
            if((string)$ip->code=='1'){
                return false;
            }
            $data = (array)$ip->data;
        }
        return $data;
    }

    //登陆页
    public function login()
    {
        return $this->fetch('index');
    }

    //登陆判断
    public function do_login(){
        $username = $_POST['username'];
        $pwd = $_POST['pwd'];
        $res = Db::name('user')->where("username='$username' and pwd='$pwd'")->select();
        if ($res!=null) {
            session('user',array('username'=>$username,'user_name'=>$res[0]['user_name']));
            $data['username'] = $username;
            // $data['ip'] = $_SERVER["REMOTE_ADDR"];
            $data['ip'] = $this->getIP();//登录ip
            // $data['city'] = $this->getCity($data['ip'])['city'];//登录城市
            $data['city'] = '';
            $data['time'] = date('Y-m-d H:i:s',time());
            $res1 = Db::name('record_login')->insert($data);
            $this->redirect('index/index/index');
        }else{
            $this->error('登录失败，账号或密码有误');
        }
    }

    //登出
    public function out_login(){
        Session::delete('user');
        $this->redirect('index/login/login');
    }

}
